<template>
  <view class="container" v-if="isLoaded">
    <!-- 地址 -->
    <scroll-view scroll-y style="height: 100vh">
      <view class="wrapper">
        <!-- address -->
        <view class="edit-c" v-if="m_addressList.length > 0">
          <view class="address-c">
            <view class="l">
              <view class="a">{{
                m_addressList[m_address_idx].FPrCityArea
              }}</view>
              <view class="u">{{ m_addressList[m_address_idx].FAddress }}</view>
              <view class="u" style="">
                <view class="n">{{
                  m_addressList[m_address_idx].FConsignee
                }}</view>
                <view class="p">{{ m_addressList[m_address_idx].FPhone }}</view>
              </view>
            </view>
            <view class="r">
              <!--   <uni-icons
                type="trash"
                size="30"
                style="margin-right: 5px"
                v-on:tap="DelAddress(address)"
              /> -->
              <u-icon
                name="edit-pen"
                size="30"
                v-on:tap="editAddress(m_addressList[m_address_idx])"
              />
            </view>
          </view>
        </view>
        <view class="add-c" v-if="m_addressList.length == 0">
          <view class="btn-add" v-on:tap="newAddress">新增收货地址</view>
        </view>
        <view class="add-c" v-if="m_addressList.length > 0">
          <view class="btn-add" v-on:tap="oca">更换收货地址</view>
        </view>

        <!-- 商品 -->
        <view class="gs">
          <view class="t"> 商品 </view>
          <view class="product">
            <image
              :src="imageUrl + m_good_detail.FProImage[0].FGoodImg"
              mode="aspectFit"
              class="image"
            />

            <view class="content">
              <view class="name">{{ m_good_detail.FName }}</view>
            </view>
            <view class="p-c">
              <view class="p">{{ m_mallPoint }}积分</view>
              <view class="q">x{{ 1 }}</view>
            </view>
          </view>
          <view style="padding: 10px 14px; display: flex; align-items: center">
            <u--input
              placeholder="添加订单备注"
              border="surround"
              v-model="form.remark"
              :maxlength="50"
            ></u--input>
          </view>
        </view>

        <!-- 金额 -->
        <view class="js">
          <view class="i">
            <view class="l">所需积分</view>
            <view class="r fwb"
              ><text class="s" style="color: #e4304d"></text
              >{{ m_mallPoint }}</view
            >
          </view>

          <!--        <view class="i" style="border-top: 1px solid #f5f5f5">
            <view class="l"></view>
            <view class="r"
              >共计{{ tCount }}件,合计:
              <text class="s red" style="margin-left: 4px">￥</text
              ><text class="s fwb red" style="font-size: 14px">{{
                (tMoney - reduceAmount + send).toFixed(2) > 0
                  ? (tMoney - reduceAmount + send).toFixed(2)
                  : 0
              }}</text></view
            >
          </view> -->
        </view>

        <!-- 提交订单按钮 -->
        <view class="b">
          <view class="btn" v-on:click="onOrderSubmit"> 立即兑换 </view>
        </view>
      </view>
    </scroll-view>

    <lee-popup :show="m_show" @open="open" @close="close">
      <view class="popup">
        <view
          class="address-c"
          v-for="(address, index) in m_addressList"
          :key="index"
          v-on:tap="(m_address_idx = index), (m_show = false)"
        >
          <view class="l">
            <view class="a">{{ address.FPrCityArea }}</view>
            <view class="u">{{ address.FAddress }}</view>
            <view class="u" style="">
              <view class="n">{{ address.FConsignee }}</view>
              <view class="p">{{ address.FPhone }}</view>
            </view>
          </view>
          <view class="r">
            <!--    <image
              style="width: 17px; height: 17px"
              v-if="m_address_idx == index"
              src="/static/images/icon-select.png"
            />
            <image
              style="width: 17px; height: 17px"
              v-else
              src="/static/images/noSelect.png"
            /> -->
          </view>

          <view
            v-if="m_address_idx == index"
            style="
              position: absolute;
              right: 0;
              top: 0;
              width: 0;
              height: 0;
              border-top: 15px solid #fe0203;
              border-right: 15px solid #fe0203;
              border-bottom: 15px solid transparent;
              border-left: 15px solid transparent;
            "
          ></view>
          <view
            v-if="m_address_idx == index"
            style="
              position: absolute;
              right: 0;
              top: 0;
              width: 18px;
              height: 18px;
              line-height: 18px;
              text-align: center;
              color: #fff;
            "
            >√</view
          >
        </view>
      </view>
    </lee-popup>
  </view>
</template>

<script>
import { onMounted, reactive, ref } from "@vue/composition-api";
import {
  uModal,
  uNavigateBack,
  uNavigateTo,
  uToast,
} from "../../utils/uniUtils";
import { reqPost } from "../../common/http.request";

export default {
  async onShow() {
    try {
      await this.GetAddressList();

      this.isLoaded = true;
    } catch (error) {
      this.isLoaded = !true;
      console.log("error", error);
      uToast("初始化失败~", "error");
      setTimeout(() => {
        uNavigateBack();
      }, 1500);
    }
  },
  onLoad({ gid, point }) {
    this.m_goods_id = gid;
    this.m_mallPoint = point;
  },
  setup(_props, _context) {
    onMounted(async function () {
      try {
        await getGoodDetail();
      } catch (error) {
        isLoaded.value = !true;
        console.log("error", error);
        uToast("初始化失败~", "error");
        setTimeout(() => {
          uNavigateBack();
        }, 1500);
      }
    });

    const m_goods_id = ref(0);
    const m_mallPoint = ref(9999999999);

    const m_addressList = ref([]);
    const m_payMethods = ref([
      {
        label: "微信支付",
        value: "wechatpay",
        name: "weixin-fill",
        selected: "checkmark-circle-fill",
        unSelected: "checkmark-circle",
        color: "#51b133",
        isPayMethod: true,
        isShow: true,
        id: 1,
      },
      /* {
        label: "余额支付",
        value: "balancepay",
        name: "rmb",
        selected: "checkmark-circle-fill",
        unSelected: "checkmark-circle",
        color: "#51b133",
        isPayMethod: false,
        isShow: false,
        id: 2,
      }, */
    ]);
    const payment_code = ref("point");
    const FPayId = ref(7);
    const balance = ref(0);
    const reduceAmount = ref(0);
    const send = ref(0);
    const m_ExpMoney = ref(0);
    const isLoaded = ref(false);
    const m_lock = ref(false);
    // const { cart, tCount, tMoney } = storeToRefs(useShop());
    const form = reactive({
      remark: "",
    });

    const m_cid = ref(0);
    const m_address_idx = ref(0 - 1);
    const m_good_detail = ref(null);

    function newAddress() {
      uNavigateTo("/pages/user/newAddress/newAddress");
    }

    async function getGoodDetail() {
      m_good_detail.value = (
        await reqPost("GetGoodsDetail", {
          goods_id: m_goods_id.value,
        })
      ).Data;
    }

    async function GetAddressList() {
      m_addressList.value = (await reqPost("GetAddressList")).Data;
      if (m_addressList.value.length > 0) {
        m_address_idx.value = 0;
        const idx = m_addressList.value.findIndex(
          (item) => item.FDefault == "1"
        );
        if (idx >= 0) {
          m_address_idx.value = idx;
        }
      }
    }

    async function AccExpMoney() {
      if (m_addressList.value.length == 0) {
        return;
      }

      m_ExpMoney.value = (
        await reqPost("AccExpMoney", {
          strJson: JSON.stringify({
            // FCmpID: "",
            Pid: m_addressList.value[0].FPrvID,
            Cid: m_addressList.value[0].FCityID,
            ArID: m_addressList.value[0].FAreaID,
            ImportFlag: 0,
          }),
        })
      ).Data;
    }

    /*    watch(
      balance,
      (n, o) => {
        if (n < tMoney.value) {
          // 判断余额是否大于商品价格
          m_payMethods.value[1].isShow = false;
        } else {
          m_payMethods.value[1].isShow = true;
        }
      },
      {
        immediate: true,
        deep: true,
      }
    ); */

    async function DelAddress(address) {
      if (address.FDefault == "1") {
        return uToast("默认地址不允许删除", "none");
      }
      if (await uModal("确定要删除吗？")) {
        let res = (
          await reqPost("DelAddress", {
            id: address.FItemID,
          })
        ).Data;

        if (res) {
          await GetAddressList();
          uToast("删除成功！");
        } else {
          uToast("删除失败！", "error");
        }
      }
    }

    function editAddress(address) {
      uNavigateTo("/pages/user/newAddress/newAddress?id=" + address.FItemID);
    }

    async function onOrderSubmit() {
      if (m_address_idx.value == -1) {
        uToast("请选择地址", "error");
        return;
      }

      if (m_addressList.value.length == 0) {
        uToast("请输入地址", "error");
        return;
      }

      if (m_lock.value) {
        return;
      }

      const m_address = m_addressList.value[m_address_idx.value];
      m_lock.value = true;
      try {
        const m_dt = (
          await reqPost("OrderSubmit", {
            J_Pid: m_address.FPrvID,
            J_Cid: m_address.FCityID,
            J_Arid: m_address.FAreaID,
            J_CmpID: 0,
            J_PayID: FPayId.value,
            J_FCouponID: m_cid.value,
            J_FCouponMoney: 0,
            J_ExpMoney: 0,
            J_FImportFlag: 0,
            J_FBillFlag: "off", // 是否要发票
            J_FConsignee: m_address.FConsignee,
            J_FPrCityArea: m_address.FPrCityArea,
            J_FAddress: m_address.FAddress,
            J_FPhone: m_address.FPhone,
            J_FMessage: form.remark,
            J_FCutIntegral: m_mallPoint.value,
            type: "0",
            FSckillDetailID: null,
            GoodsID: m_goods_id.value,
          })
        ).Data;

        const J_KInterID = m_dt.J_KInterID;
        setTimeout(() => {
          uNavigateTo(`/pages/order/exchangeSuccess`);
        }, 0);
      } catch (error) {
        console.log("error :>> ", error);
      } finally {
        m_lock.value = false;
      }

      console.log("onOrderSubmit");
    }

    function onCheckPay(index) {
      m_payMethods.value.forEach((e) => {
        e.isPayMethod = false;
      });
      m_payMethods.value[index].isPayMethod =
        !m_payMethods.value[index].isPayMethod;
      payment_code.value =
        m_payMethods.value[
          m_payMethods.value.findIndex((e) => e.isPayMethod)
        ].value;
      FPayId.value =
        m_payMethods.value[
          m_payMethods.value.findIndex((e) => e.isPayMethod)
        ].id;
    }

    function onRecharge() {
      console.log("onRecharge");
    }

    const m_show = ref(false);
    function oca() {
      m_show.value = true;
    }

    function open() {
      console.log("open");
      m_show.value = true;
    }

    function close() {
      m_show.value = !true;
      console.log("close");
    }

    return {
      m_show,
      m_addressList,
      GetAddressList,
      newAddress,
      isLoaded,
      DelAddress,
      editAddress,
      form,
      onOrderSubmit,
      m_payMethods,
      payment_code,
      onCheckPay,
      onRecharge,
      balance,
      reduceAmount,
      send,
      AccExpMoney,
      m_ExpMoney,
      m_cid,
      m_address_idx,
      oca,
      open,
      close,
      m_good_detail,
      m_goods_id,
      m_mallPoint,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "./scss/cartOrder.scss";
</style>
